package adminuser

import (
	"fmt"
	"net/http"

	"gitee.com/zoneaurora/shop/internal/common"
	"gitee.com/zoneaurora/shop/internal/dto"
	"gitee.com/zoneaurora/shop/internal/logic/admin/base"
	"gitee.com/zoneaurora/shop/internal/model"
	"gitee.com/zoneaurora/shop/internal/vo"
	"github.com/gin-gonic/gin"
)

type AdminUserLogic struct {
	base.BaseLogic[model.AdminUser]
}

func NewAdminUserLogic() *AdminUserLogic {
	return &AdminUserLogic{
		BaseLogic: base.BaseLogic[model.AdminUser]{
			DB: common.DB(),
		},
	}
}

func (a *AdminUserLogic) Select(c *gin.Context) {
	//  获取请求参数
	id := c.Param("id")

	var model model.AdminUser
	if err := a.DB.First(&model, id).Error; err != nil {
		common.JSON(c, http.StatusInternalServerError, "查询数据失败", nil)
		return
	}
	common.JSON(c, http.StatusOK, "查询数据成功", dto.ToAdminUserDto(model))
}

func (a *AdminUserLogic) GetPageList(c *gin.Context) {
	//  获取请求参数
	var requestParam vo.Pagination
	c.Bind(&requestParam)
	if requestParam.Order != "asc" {
		requestParam.Order = "desc"
	}
	if requestParam.SortName == "" {
		requestParam.SortName = "updated_at"
	}
	order := fmt.Sprintf("%s %s", requestParam.SortName, requestParam.Order)

	var models []model.AdminUser
	var total int64
	res := a.DB.Find(&models)
	if res.Error != nil {
		common.JSON(c, http.StatusInternalServerError, "查询数据失败", nil)
		return
	}
	total = res.RowsAffected
	err := a.DB.Offset((requestParam.Page - 1) * requestParam.Size).
		Order(order).Limit(requestParam.Size).Find(&models).Error
	if err != nil {
		common.JSON(c, http.StatusInternalServerError, "查询数据失败", nil)
		return
	}
  var adminDtos []dto.AdminUserDto
  for _, v := range models {
    adminDtos = append(adminDtos, dto.ToAdminUserDto(v))
  }
	common.JSON(c, http.StatusOK, "查询数据成功", gin.H{
		"list":  adminDtos,
		"total": total,
	})
}
